<?php 
namespace app\common\service;

use app\common\libs\PHPMailer;
use think\Config;
class MailService{
	
	public static $instance = null;
	
	private function __construct(){
	}
	public static function getInstance(){
		if(self::$instance == null){
			self::$instance = new self();
		}
		return self::$instance;
	}
	
	
	
	/**
	 * 功能：调用PHPMailer发送邮件
	 * @author lijuan
	 * @param string $touser 接收人邮箱
	 * @param string $title 标题
	 * @param string $body 正文
	 * @param files $atts 附件
	 * @return bool
	 */
	function sendmail($touser, $title, $body, $atts=FALSE)
	{
		$title = iconv("UTF-8", "GB2312", $title);
		$title = "=?GB2312?B?".base64_encode($title)."?=";
		$attpath = Config::get("attachment_path_pre"); //设置附件路径
		$account = Config::get('mail_config');
		var_dump($account,$attpath);
		$mail = new PHPMailer();
		$mail->IsSMTP();                   // 设置使用 SMTP
		$mail->Host = $account['server'];          // 指定的 SMTP 服务器地址
		$mail->SMTPAuth = true;  // 设置为安全验证方式
		$mail->Username = $account['username'];    // SMTP 发邮件人的用户名
		$mail->Password = $account['password'];             // SMTP 密码
	
		$mail->From = $account['username'];
		$mail->FromName = "=?GB2312?B?" . base64_encode(iconv("UTF-8", "GB2312", '快法务')) . "?=";
		$mail->AddAddress($touser);
		$mail->AddBCC("mailmonitor@kuaifawu.com");
	
		$mail->WordWrap = 50; // set word wrap to 50 characters
		//$mail->AddAttachment("/var/tmp/file.tar.gz");     // 加附件
		//$mail->AddAttachment("/tmp/image.jpg", "new.jpg");  // 附件，也可选加命名附件
	
		if($atts){
			foreach($atts as $v){
				if(is_array($v)){
					$tmp = $v;
					if (count($tmp) > 2) {//这里大于两个参数表示为自定义的附件
						$tmp[0] = $attpath . $tmp[0];
					}else{
						$tmp[0] = ROOT_PATH . 'Uploads' . $tmp[0];
					}
					$tmp[1] = iconv("UTF-8", "GB2312", $tmp[1]);
					$mail->addAttachment($tmp[0], $tmp[1]);
				}else{
					$mail->addAttachment($attpath . $v);
				}
			}
		}
	
		$mail->IsHTML(true);        // 设置邮件格式为 HTML
	
		$mail->Subject = $title;    // 标题
		$mail->Body  = $body;       // 内容
		//$mail->AltBody = "This is the body in plain text for non-HTML mail clients"; // 附加内容
	
		if(!$mail->Send())
		{
			echo "邮件发送失败<p>";
			echo "错误: " . $mail->ErrorInfo;
			exit;
		}
		return true;
	}
	
}
?>